package com.example;

import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.AbandonedConfig;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import java.util.HashMap;
import java.util.Map;

/**
 * @author shanchong
 * @date 2021/4/13
 **/
public class MyObjectPoolDemo {

    public static void main(String[] args) throws Exception {
        PooledObjectFactory<MyObject> pooledObjectFactory = new BasePooledObjectFactory<MyObject>(){

            @Override
            public MyObject create() throws Exception {
                return new MyObject();
            }

            @Override
            public PooledObject<MyObject> wrap(final MyObject obj) {
                return new DefaultPooledObject<>(obj);
            }
        };
        GenericObjectPoolConfig<MyObject> objectGenericObjectPoolConfig = new GenericObjectPoolConfig<>();
        objectGenericObjectPoolConfig.setMaxTotal(Integer.MAX_VALUE);
        objectGenericObjectPoolConfig.setMaxIdle(4);
        objectGenericObjectPoolConfig.setMinIdle(2);
        AbandonedConfig abandonedConfig = new AbandonedConfig();
        abandonedConfig.setRemoveAbandonedTimeout(1);
//        abandonedConfig.setRemoveAbandonedOnMaintenance(true);
        abandonedConfig.setRemoveAbandonedOnBorrow(true);
        GenericObjectPool<MyObject> genericObjectPool =
                new GenericObjectPool<MyObject>(pooledObjectFactory, objectGenericObjectPoolConfig, abandonedConfig);
        MyObject myObject = genericObjectPool.borrowObject();
        System.out.println(myObject);
        for (int i = 0; i < 1000; i++) {
            Thread.sleep(1000);
            MyObject myObject1 = genericObjectPool.borrowObject();
            System.out.println(i+"."+ myObject1);
            System.out.println(genericObjectPool.getNumActive() + "-" + genericObjectPool.getNumIdle());
            genericObjectPool.returnObject(myObject1);
        }
        Thread.sleep(10000);
        System.out.println(genericObjectPool.getNumActive() + "-" + genericObjectPool.getNumIdle());
    }

}
